package xiaodong.train.logic;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import xiaodong.train.Constants;

public class Update {
	private DefaultHttpClient httpclient = null;

	public Update(DefaultHttpClient client) {
		this.httpclient = client;
		client.getParams()
				.setParameter(
						HTTP.USER_AGENT,
						"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; TEN)"); //$NON-NLS-1$

	}

	public boolean isNewestVersion() {
		String currentVersion = Constants.CUR_VERSION;
		String newestVersion = null;
		HttpGet get = new HttpGet(Constants.UPDATE_URL);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseBody = null;
		try {
			responseBody = httpclient.execute(get, responseHandler);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		newestVersion = getNewestVersion(responseBody);
		if (newestVersion == null)
			return true;

		System.out.println("当前版本：" + currentVersion);
		System.out.println("最新版本：" + newestVersion);
		if (currentVersion.equalsIgnoreCase(newestVersion.trim())) {
			return true;
		}
		return false;
	}

	public String getNewestVersion(String html) {
		Document doc = Jsoup.parse(html);
		Element currentVersion = doc.getElementById("currentVersion");
		if (currentVersion != null)
			return currentVersion.attr("value");
		else
			return null;
	}
}
